#!/usr/bin/python3

import os
import sys


def process(file: str):
    cmd = str("clang-format -style=file") + \
        " -i " + file + " >> /tmp/clang-format.log"
    # print(cmd)
    os.system(cmd)
    pass


def file_filter(file_name: str):
    if file_name.endswith((".c", ".cc", ".cpp", ".h")):
        process(file_name)
        pass


def for_each_file(file_path: str):
    for parent, _, files in os.walk(file_path):
        for file in files:
            file_name = os.path.join(parent, file)
            file_filter(file_name)


if __name__ == "__main__":
    # 脚本当前目录或上级目录必须包含 .clang-format 文件
    if len(sys.argv) != 2:
        print("\n脚本当前目录或上级目录必须包含 .clang-format 文件\n")
        print("\nusage:  ./clang-format [path or file]\n")
        exit(1)
    file_or_path = os.path.abspath(sys.argv[1])

    if not os.path.exists("/usr/bin/clang-format"):
        print("/usr/bin/clang-format not exit. try install clang-format")
        exit(2)

    if os.path.isdir(file_or_path):
        for_each_file(file_or_path)
    elif os.path.isfile(file_or_path):
        file_filter(file_or_path)
    else:
        print(file_or_path, "not file or path")
    exit(0)
